<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>项目管理</el-breadcrumb-item>
      <el-breadcrumb-item>合作方管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-row :gutter="10">
      <el-col :span="5">
        <el-card>
          <div slot="header">
            <span style="font-size: 18px; font-weight: 600">公司</span>
          </div>
          <div v-for="(item, index) in this.companyTree" :key="index" :timestamp="item.time"  :style="queryInfo.query.partner_id===item.id?selfstyle:''" >
              <span
                class="custom-tree-node"
                @mouseenter="treeMouseOver($event)"
                @mouseleave="treemouseLeave($event)"
              >
              <el-button type="text" @click="nodeClick(item)" >
                <i class="el-icon-office-building"></i>
                <span> {{ item.name }} 【{{ item.id }}】</span>
              </el-button>
              <span class="node-none" @click="getDepartDataById(item)">
                <i class="el-icon-edit"></i>
              </span>
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="19">
        <!-- 列表卡片 -->
        <el-card v-show="showCardName === 'list'">
          <h2 style="margin: 0 0 10px 0">
            {{ defaultDepartment }}（{{ total }}）
          </h2>
          <!-- 搜索区 -->
          <el-form
            ref="searchFormRef"
            :inline="true"
            :model="queryInfo.query"
            size="mini"
          >
            <el-form-item label="机构级别" prop="level">
              <el-select
                v-model="queryInfo.query.level"
                placeholder="请选择"
                filterable
                clearable
              >
                <el-option key="1" label="一级机构" value="1"> </el-option>
                <el-option key="2" label="二级机构" value="2"> </el-option>
                <el-option key="3" label="三级机构" value="3"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryInfo.query.keywords"
                placeholder="请输入机构全称、简称、ID或代码"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                class="theme-background-color"
                size="mini"
                @click="searchList"
              >
                搜索
              </el-button>
              <el-button size="mini" @click="resetSearchForm"> 重置 </el-button>
            </el-form-item>
          </el-form>

          <!-- 操作区域 -->
          <div>
            <el-button
              class="theme-background-color"
              icon="el-icon-user"
              size="mini"
              @click="cardSwitch('partner')"
            >
              新增公司
            </el-button>
            <el-button
              class="theme-background-color"
              icon="el-icon-s-home"
              size="mini"
              @click="cardSwitch('account')"
            >
              新增机构
            </el-button>
          </div>

          <el-table
            :data="tableData"
            style="width: 100%;margin-bottom: 20px;"
            row-key="id"
            border
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column label="机构简称【ID】" sortable min-width="300">
              <template slot-scope="scope">
                {{ scope.row.short_name + '【' + scope.row.id + '】' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="机构全称"
              width="280"
              align="center">
            </el-table-column>
            <el-table-column
              prop="org_code"
              label="机构代码"
              width='140'
              align='center'>
            </el-table-column>
            <el-table-column
              label="机构级别"
              width='80'
              align='center'>
              <template slot-scope="scope">
                {{ scope.row.level + '级' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="status.name"
              label="状态"
              width='80'
              align='center'>
            </el-table-column>
            <el-table-column label="操作" width="280"  align="center" fixed="right">
              <template slot-scope="scope">
                <el-link
                  type="danger"
                  v-if="scope.row.status.id === 1"
                  @click="enable(scope.row)"
                >
                  禁用
                </el-link>
                <el-link
                  type="primary"
                  v-if="scope.row.status.id === 2"
                  @click="enable(scope.row)"
                >
                  启用
                </el-link>
                &nbsp;
                <el-link type="primary" @click="getAccountDataById(scope.row)">
                  编辑
                </el-link>
                &nbsp;
                <el-link type="primary" @click="invoiceInfo(scope.row)">
                  开票信息
                </el-link>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页区域 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>

        </el-card>

        <!-- 新增公司卡片 -->
        <el-card v-show="showCardName === 'partner'">
          <div slot="header">
            <span style="font-size: 18px; font-weight: 600; color: #66b1ff">
            {{ editAccount_id === '' ? '新增公司' : '编辑公司' }}
            </span>
          </div>
          <el-form
            :model="addPartnerForm"
            :rules="addPartnerFormRules"
            ref="addPartnerFormRef"
            label-width="100px"
            class="accountForm"
          >
            <el-form-item label="公司名称" prop="name">
              <el-input v-model="addPartnerForm.name"></el-input>
            </el-form-item>
            <el-form-item label="公司简称" prop="short_name">
              <el-input v-model="addPartnerForm.short_name"></el-input>
            </el-form-item>
            <el-form-item label="公司类型" prop="type">
              <el-select
                v-model="addPartnerForm.type"
                placeholder="请选择"
                filterable
                clearable
              >
                <el-option key="1" label="财险公司" :value="typeof addPartnerForm.type == 'string' ? '1' : 1"> </el-option>
                <el-option key="2" label="寿险公司" :value="typeof addPartnerForm.type == 'string' ? '2' : 2"> </el-option>
                <el-option key="3" label="银行" :value="typeof addPartnerForm.type == 'string' ? '3' : 3"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="cardSwitch('list')"> 取 消 </el-button>
              <el-button class="theme-background-color" @click="savePartner"
                >保 存</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
        <!-- 新增公司卡片 -->

        <!-- 新增\编辑机构 -->
        <el-card v-show="showCardName === 'account'">
          <div slot="header">
            <span style="font-size: 18px; font-weight: 600; color: #66b1ff">{{
              editAccount_id === '' ? '新增机构' : '编辑机构'
            }}</span>
          </div>
          <el-form
            :model="accountForm"
            :rules="accountFormRules"
            ref="accountFormRef"
            label-width="100px"
            class="accountForm"
          >
            <el-form-item label="机构名称" prop="name">
              <el-input v-model="accountForm.name"></el-input>
            </el-form-item>
            <el-form-item label="机构简称" prop="short_name">
              <el-input v-model="accountForm.short_name"></el-input>
            </el-form-item>
            <el-form-item label="合作方机构代码" prop="org_code">
              <el-input v-model="accountForm.org_code"></el-input>
            </el-form-item>
            <el-form-item label="机构级别" prop="level">
              <el-select
                v-model="accountForm.level"
                placeholder="请选择"
                filterable
                clearable
                @change="onSelectedDrug($event)"
                :disabled="editAccount_id !=''"
              >
                <el-option key="1" label="一级机构" :value="typeof accountForm.level == 'string' ? '1' : 1"> </el-option>
                <el-option key="2" label="二级机构" :value="typeof accountForm.level == 'string' ? '2' : 2"> </el-option>
                <el-option key="3" label="三级机构" :value="typeof accountForm.level == 'string' ? '3' : 3"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上级机构" prop="pid" v-show="look"
            :rules="look==true?
              [ {required: true,message: '请选择',trigger: 'change'}]:[]
              "
            >
              <el-select
                v-model="accountForm.pid"
                placeholder="请选择"
                filterable
                clearable
              >
                <el-option
                  v-for="item in allHigherOrg"
                  :key="item.id"
                  :label="item.name"
                  :value="typeof accountForm.pid == 'string'? + item.id + '': item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="cardSwitch('list')"> 取 消 </el-button>
              <el-button class="theme-background-color" @click="saveAccountInfo"
                >保 存</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
        <!-- 新增\编辑机构 -->

        <!-- 开票公司信息 -->
        <el-card v-show="showCardName === 'invoice'">
          <div slot="header">
            <span style="font-size: 18px; font-weight: 600; color: #348a5b ">
              开票信息
            </span>
            <span style="float:right;">
              <el-button size="text" style="color: #348A5B;" @click="editInovice()"><i class="el-icon-edit-outline"></i>编辑开票信息
              </el-button>
            </span>
          </div>
          <el-form
            :model="invoiceForm"
            label-width="100px"
            class="accountForm"
          >
            <el-form-item label="公司名称" prop="company_name">
              {{invoiceForm.company_name}}
            </el-form-item>
            <el-form-item label="纳税人识别码" prop="invoice_no">
              {{ invoiceForm.invoice_no }}
            </el-form-item>
            <el-form-item label="注册地址" prop="address">
              {{invoiceForm.address}}
            </el-form-item>
            <el-form-item label="注册电话" prop="phone">
              {{invoiceForm.phone}}
            </el-form-item>
            <el-form-item label="开户银行" prop="bank">
              {{invoiceForm.bank}}
            </el-form-item>
            <el-form-item label="银行账户" prop="account">
              {{invoiceForm.account}}
            </el-form-item>
            <el-form-item>
              <el-button @click="cardSwitch('list')"> 返 回 </el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <!-- 开票公司信息 -->

        <!-- 编辑开票信息 -->
        <el-card v-show="showCardName === 'editInvoice'">
          <div slot="header">
            <span style="font-size: 18px; font-weight: 600; color: #348a5b ">
              开票信息
            </span>
          </div>
          <el-form
            :model="invoiceForm"
            :rules="invoiceFormRules"
            ref="invoiceFormRef"
            label-width="100px"
            class="accountForm"
          >
            <el-form-item label="公司名称" prop="company_name">
              <el-input v-model="invoiceForm.company_name"></el-input>
            </el-form-item>
            <el-form-item label="纳税人识别码" prop="invoice_no">
              <el-input v-model="invoiceForm.invoice_no"></el-input>
            </el-form-item>
            <el-form-item label="注册地址" prop="address">
              <el-input v-model="invoiceForm.address"></el-input>
            </el-form-item>
            <el-form-item label="注册电话" prop="phone">
              <el-input v-model="invoiceForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="开户银行" prop="bank">
              <el-input v-model="invoiceForm.bank"></el-input>
            </el-form-item>
            <el-form-item label="银行账户" prop="account">
              <el-input v-model="invoiceForm.account"></el-input>
            </el-form-item>
            <el-form-item>
            <el-button @click="cardSwitch('list')"> 取 消 </el-button>
            <el-button class="theme-background-color" @click="saveInvoice">
              保 存
            </el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <!-- 编辑开票信息 -->

      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selfstyle: {
        backgroundColor: "#d9e3f1"
      },
      // 公司树状结构
      tableData: [],
      // 公司ID
      partner_id: '',
      firstLoad: true,
      // 组织架构树
      companyTree: [],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      // 获取平台用户列表的参数对象
      queryInfo: {
        query: {
          level: '',
          keywords: '',
          // 公司ID
          partner_id: ''
        },
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 10
      },
      accountList: [],
      total: 0,
      allHigherOrg: [],
      departmentsadd: [],
      roles: [],
      defaultDepartment: '机构',
      // 机构编辑栏
      accountForm: {
        org_id: '',
        name: '',
        short_name: '',
        org_code: '',
        level: '',
        pid: ''
      },
      // 机构编辑栏校验规则
      accountFormRules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        short_name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        org_code: [
          { required: true, message: '请输入', trigger: 'number' }
        ],
        level: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      // 公司数据栏
      addPartnerForm: {
        name: '',
        short_name: '',
        type: ''
      },
      // 公司参数校验
      addPartnerFormRules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        short_name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        type: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      // 开票信息参数
      invoiceForm: {
        company_name: '',
        invoice_no: '',
        address: '',
        phone: '',
        bank: '',
        account: '',
        pid: ''
      },
      invoiceFormRules: {
        company_name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, message: '最少输入一个字符', trigger: 'blur' }
        ],
        invoice_no: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      // 账号的主键，用于编辑账号
      editAccount_id: '',
      // 右侧默认展示的卡片
      showCardName: 'list',
      look: true
    }
  },
  created() {
    // 获取公司列表
    this.getPartnerList()
    // 获取查询下拉框数据
    this.getSelectData()
  },
  methods: {
    async getPartnerList() {
      const { data: res } = await this.$http.get('/admin/Partner/getList')
      if (res.meta.status !== 200) {
        return this.$message.error('获取组织架构失败！')
      }
      this.companyTree = res.data
      if (this.queryInfo.query.partner_id == '') {
        this.queryInfo.query.partner_id = this.companyTree[0].id
        this.getListData()
      }
    },
    async getSelectData() {
      const { data: dep } = await this.$http.post('/admin/data/find', {
        code: 'department,role'
      })

      if (dep.meta.status !== 200) {
        return this.$message.error('获取下拉数据失败！')
      }
      this.departments = dep.data.department
      this.departmentsadd = dep.data.department
      this.roles = dep.data.role
    },
    async selectDepartLevel(val) {
      const { data: dep } = await this.$http.post('/admin/data/find', {
        code: 'department',
        level: val - 1
      })

      if (dep.meta.status !== 200) {
        return this.$message.error('获取下拉数据失败！')
      }
      this.departmentsadd = dep.data.department
    },

    async getListData() {
      // 返回数据重命名为res

      const { data: res } = await this.$http.post(
        '/admin/Partner/getPartnerOrg',
        this.queryInfo
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.tableData = res.data.list
      this.total = res.data.total
    },
    searchList() {
      this.queryInfo.pagenum = 1
      this.getListData()
    },
    resetSearchForm() {
      this.$refs.searchFormRef.resetFields()
      this.getListData()
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getListData()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getListData()
    },
    // 启用\禁用机构
    async enable(data) {
      console.log(data)
      if (data.status.id == 1) {
        var msg = '是否确认禁用' + data.name + '【' + data.id + '】' + '？禁用后不可使用'
      } else {
        var msg = '是否确认启用' + data.name + '【' + data.id + '】' + '？'
      }
      // 弹框询问
      const confirmResult = await this.$confirm(
        msg, '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消操作')
      }
      const { data: res } = await this.$http.post('/admin/Partner/onOffStatus', {
        // 参数
        org_id: data.id, status: data.status.id
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getListData()
    },
    async onSelectedDrug(event) {
      // this.accountForm.pid = ''
      if (event == 1) {
        this.accountFormRules.pid = []
        this.look = false
      } else {
        this.look = true
      }
      const url = '/admin/Partner/getHigherOrg'
      const { data: res } = await this.$http.post(url, { level: event, partner_id: this.queryInfo.query.partner_id })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.allHigherOrg = res.data
    },

    showResetPassDialog(id) {
      this.resetPassDialogVisible = true
    },
    // 点击公司名称
    async nodeClick(data) {
      this.queryInfo.query.partner_id = data.id
      const url = '/admin/Partner/getPartnerOrg'
      const { data: res } = await this.$http.post(url, this.queryInfo)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.tableData = res.data.list
      this.total = res.data.total
    },
    // 编辑保存
    async saveAccountInfo() {
      this.$refs.accountFormRef.validate(async (valid) => {
        if (!valid) return
        console.log(this.accountForm)
        var url = ''
        if (this.editAccount_id === '') {
          this.accountForm.partner_id = this.queryInfo.query.partner_id
          url = '/admin/Org/addOrg'
        } else {
          this.accountForm.uid = this.editAccount_id
          url = '/admin/Partner/editOrg'
        }
        const { data: res } = await this.$http.post(url, this.accountForm)

        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getListData()
        this.clearAllForm()
        this.showCardName = 'list'
      })
    },
    // 新增公司
    async savePartner() {
      this.$refs.addPartnerFormRef.validate(async (valid) => {
        if (!valid) return
        var url = ''
        if (this.editAccount_id === '') {
          url = '/admin/Partner/addPartner'
        } else {
          this.addPartnerForm.partner_id = this.editAccount_id
          url = '/admin/Partner/editPartner'
        }
        const { data: res } = await this.$http.post(url, this.addPartnerForm)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getListData()
        this.getPartnerList()
        this.showCardName = 'list'
      })
    },
    // 点击编辑机构按钮
    async getAccountDataById(data) {
 console.log(data.pid)
     this.accountForm.name = data.name
      this.accountForm.short_name = data.short_name
      this.accountForm.org_code = data.org_code
      this.accountForm.partner_id = data.partner_id
      this.accountForm.pid = data.pid
      this.accountForm.level = data.level
      this.accountForm.org_id = data.id
      this.showCardName = 'account'
      this.editAccount_id = data.id
      this.onSelectedDrug(data.level)
    },
    // 根据传入的卡片名，控制显示
    cardSwitch(name) {
      this.showCardName = name
      this.clearAllForm()
    },
    // 清除表单的内容
    clearAllForm() {
      this.editAccount_id = ''
      this.$refs.addPartnerFormRef.resetFields()
      this.$refs.accountFormRef.resetFields()
    },
    saveDepartInfo() {
      this.$refs.departFormRef.validate(async (valid) => {
        if (!valid) return
        // 新增的请求
        // const { data: res } = await this.$http.post(
        //   'addProduct',
        //   this.addForm
        // )
        // 修改的请求
        // const { data: res } = await this.$http.put(
        //   'addProduct/' + this.$route.query.id,
        //   this.addForm
        // )
        var url = ''
        if (this.editDepart_id === '') {
          url = '/admin/department/add'
        } else {
          this.departForm.code = this.editDepart_id
          url = '/admin/department/edit'
        }
        const { data: res } = await this.$http.post(url, this.departForm)

        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)

        // 更新组织架构树
        this.getCompanyTree()
        // 更新列表
        this.getListData()
        this.showCardName = 'list'
      })
    },
    mouseOver(e) {
      console.log(e)
      if (e.target.lastElementChild) {
        // 鼠标移入移出要做个判断，鼠标是否在树节点上，如果在才赋值，不在就不要赋值，否则会一直报错
        e.target.lastElementChild.setAttribute('class', 'node-blocks') // 设置显示样式
      }
    },
    // 鼠标移入移出事件
    treeMouseOver(e) {
      if (e.target.lastElementChild) {
        // 鼠标移入移出要做个判断，鼠标是否在树节点上，如果在才赋值，不在就不要赋值，否则会一直报错
        e.target.lastElementChild.setAttribute('class', 'node-block') // 设置显示样式
      }
    },
    treemouseLeave(e) {
      if (e.target.lastElementChild) {
        e.target.lastElementChild.setAttribute('class', 'node-none') // 设置隐藏样式
      }
    },
    // 点击编辑公司
    async getDepartDataById(data) {
      this.cardSwitch('partner')
      this.editAccount_id = data.id
      this.addPartnerForm.name = data.name
      this.addPartnerForm.short_name = data.short_name
      this.addPartnerForm.type = data.type
    },
    // 查看开票信息
    async invoiceInfo(data) {
      const url = 'admin/Org/getInvoiceInfo'
      const { data: res } = await this.$http.post(url, { org_id: data.id })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.cardSwitch('invoice')
      this.invoiceForm.company_name = res.data.company_name
      this.invoiceForm.invoice_no = res.data.invoice_no
      this.invoiceForm.address = res.data.address
      this.invoiceForm.phone = res.data.phone
      this.invoiceForm.bank = res.data.bank
      this.invoiceForm.account = res.data.account
      this.invoiceForm.org_id = data.id
    },
    editInovice() {
      this.cardSwitch('editInvoice')
    },
    async saveInvoice () {
      this.$refs.invoiceFormRef.validate(async (valid) => {
        if (!valid) return ''
        const url = 'admin/Org/editInvoice'
        const { data: res } = await this.$http.post(url, this.invoiceForm)
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getListData()
        this.getPartnerList()
        this.showCardName = 'list'
      })
    }
  }
}
</script>

<style lang="less" scoped>
.accountForm,
.departForm {
  width: 500px;

  .el-select,
  .el-date-editor {
    width: 400px !important;
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.node-none {
  display: none;
}
.node-block {
  display: inline;
}
.node-blocks {
  background-color: #8C939D;
}
</style>
